/* template
 * template
 */
#include <errno.h>
#include <stdio.h>
//#include <glib.h>
#include "glib.h"
#include <gio/gio.h>
#include <libxml/encoding.h>
#include <libxml/xmlwriter.h>
#include "sqlite3.h"

int tmp_sql_callback(void *ptr, int n_column, char **column_value, char **column_name)
{
  int rc = 0, i = 0;
  xmlNodePtr root_node = NULL, node = NULL;

  if (n_column == 0) {
    g_debug("sql: column is 0\n");
    rc = 1;
    goto err;
  }
  if (ptr) {
    root_node = ptr;
    node = xmlNewChild (root_node, NULL, BAD_CAST "child", NULL);
    for (i = 0; i < n_column; i++) {
      if (column_value[i])
        xmlNewProp (node, BAD_CAST column_name[i], BAD_CAST column_value[i]);
    }
  }
// DEBUG("array:%s", json_object_get_string(obj));
err:
  return rc;
}
#define MY_ENCODING "ISO-8859-1"

int
main (int argc, char *argv[])
{
	sqlite3 *sql = NULL;
  GSettings *settings;
  char *errmsg = NULL;
	const char *obj_str = NULL;
  int rc = 0;
  gchar statement[1024] = {0};
  GString *string;
 // GError *error;

	g_setenv ("GSETTINGS_SCHEMA_DIR", ".", FALSE);
	g_setenv ("G_MESSAGES_DEBUG", "all", TRUE);

  g_debug ("hello template\n");
  string = g_string_new ("");

  xmlDocPtr doc;
  xmlNodePtr collector = NULL, now = NULL;
  xmlChar *xmlbuff, *id = NULL;
  int buffersize;

  doc = xmlNewDoc (BAD_CAST "1.0");
  collector = xmlNewNode (NULL, BAD_CAST "collector");
  xmlDocSetRootElement (doc, collector);
	settings = g_settings_new ("org.gtk.ts");
	obj_str = g_settings_get_string(settings, "db-name");
	g_print("sqlname:%s\n", obj_str);// & 0x00ff);
  //rc = sqlite3_open(obj_str, &sql);
  rc = sqlite3_open("../../../collector/db/ts-3.1.1.db", &sql);
  if (rc != SQLITE_OK) {
          perror(sqlite3_errmsg(sql));
          goto out;
  }
  snprintf (statement, sizeof(statement),
      "select * from software where id in(select parent_id from '1.device');");
  rc = sqlite3_exec(sql, statement, tmp_sql_callback, collector, &errmsg);
  if (rc != SQLITE_OK) {
    g_warning("SELECT:%s:%s:%d\n", statement, errmsg, rc);
  }
  now = collector->children;
  while (now)
  {
    id = xmlGetProp (now, BAD_CAST "id");
    snprintf (statement, sizeof(statement),
        "select * from '1.device' where parent_id = %s;", id);
    rc = sqlite3_exec(sql, statement, tmp_sql_callback, now, &errmsg);
    if (rc != SQLITE_OK) {
      g_warning("SELECT:%s:%s:%d\n", statement, errmsg, rc);
    }
    now = now->next;
 //   now = xmlNextElementSibling (now);
  }
  xmlDocDumpFormatMemory (doc, &xmlbuff, &buffersize, 1);
  g_debug ("xml:%s\n", (char *) xmlbuff);
  xmlSaveFile ("test.xml", doc);
  /*
  FILE *out = NULL;
  out = fopen ("test.xml", "r+");
  xmlDocDump (out, doc);
  if (out)
    fclose (out);
  */
  xmlFree (xmlbuff);
  xmlFreeDoc (doc);
out:
  g_string_free(string, TRUE);
}
